<?php

namespace App\Models;

use App\Events\ManagerMoneyChangeEvent;
use App\Events\PlayerMoneyChangeEvent;
use App\Models\Pay as PayModel;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use SoapClient;
use SoapParam;

class Player extends Model
{
    use SoftDeletes;

    /**
     * 应该被调整为日期的属性
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    protected $table ='player';
    protected $fillable = ['server_id','acc','pwd'];

    public static function getPlayer($server,$acc){
        $player=Player::where('server_id',$server->id)->where('acc',$acc)->first();
        return $player;
    }

    public function parent(){
        if ($this->player_pid>0){
            $player= Player::where('server_id',$this->server_id)->where('player_id',$this->player_pid)->first();
            return $player;
        }else{
            return null;
        }
    }

    /**
     * @param $pay
     * @return void
     */
    public function Recharge(PayModel $pay): void
    {
        $server = Server::find($pay->server_id);
        $money = $pay->money * config('conf.oneRMBToMoney');
        // 玩家充值
        $this->money += $money;
        $this->save();
        event(new PlayerMoneyChangeEvent($server->user_id, $pay->server_id, $pay->player_id, 3, 1, $money, 0, $this->money, '玩家充值'.($pay->payway==1?'(微信)':'(支付宝)'),null,$pay->order_num));

        // 玩家推荐人
        $parent=$this->parent();
        if ($parent){
            $money_recommend=$money*$parent->recommend_ratio/100;
            $parent->money += $money_recommend;
            if ($parent->is_agent)
                $parent->money_agent += $money_recommend/config('conf.oneRMBToMoney');
            $parent->save();
            event(new PlayerMoneyChangeEvent($server->user_id, $pay->server_id, $parent->player_id, 4, 1, $money_recommend, 0, $parent->money, '推荐玩家充值奖励',null,$pay->order_num));
        }

        // 服主
        $manager = User::find($pay->manager_id);
        $manager->Recharge($pay,true);

    }

}
